package com.minstone.common.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class WebUtil {
	private static final Logger LOGGER = Logger.getLogger(WebUtil.class);

	public static Map parserParam(Map param) {
		Map result = new HashMap();
		Iterator ite = param.keySet().iterator();
		while (ite.hasNext()) {
			String key = (String) ite.next();
			String[] args = (String[]) param.get(key);
			if (args != null) {
				result.put(key, args[0]);

			}

		}
		return result;

	}

	public static Map getParamMap(HttpServletRequest request) {
		Map result = new HashMap();
		Map temp = request.getParameterMap();
		Iterator ite = temp.keySet().iterator();
		while (ite.hasNext()) {
			String key = (String) ite.next();
			String[] arge = (String[]) temp.get(key);
			if (arge.length > 0 && StringUtils.isNotEmpty(arge[0])
					&& !"\"null\"".equals(arge[0]) && !"null".equals(arge[0])) {
				result.put(key, arge[0].trim());
			}

		}
		return result;
	}

	public static Map getParamMap(ServletRequest request) {
		Map result = new HashMap();
		Map temp = request.getParameterMap();
		Iterator ite = temp.keySet().iterator();
		while (ite.hasNext()) {
			String key = (String) ite.next();
			String[] arge = (String[]) temp.get(key);

			if (arge.length > 0) {
				result.put(key, arge[0]);

			}

		}
		return result;
	}
	
	//通过地址栏传过来的参数转换成编码格式
	public static Map getParameterMapToEncoding(String queryString,  String encoding) {
		Map mapParamters = new HashMap();
		if(queryString == null ||"".equals(queryString)){
			return mapParamters;
		}
		String[] paramters = queryString.split("&");
		for (int i = 0; i < paramters.length; i++) {
			int index = paramters[i].indexOf("=");
			if(index < 1 ){
				continue;
			}
			String lValue = paramters[i].substring(0, index);
			String rValue = paramters[i].substring(index + 1);
			String decodeValue = null;
			try {
				decodeValue = URLDecoder.decode(rValue,encoding);
			} catch (UnsupportedEncodingException e) {
				LOGGER.error(e.getMessage(), e);
				return mapParamters;
			}
			mapParamters.put(lValue,decodeValue);
		}
		return mapParamters;
	}

}
